<?php
namespace app\common\model;

/**
 * 模型基类，所有模型必须继承此类
 * 状态码：
 * 200：请求成功
 * 201：创建成功
 * 202：更新成功
 * 400: 无效请求
 * 401：未授权
 * 403：禁止访问
 * 404：请求资源不存在
 * 500：内部错误
 * Class Base
 * @package zzcms\common\model
 */
class Base extends \think\Model
{
    protected $pk = 'id';
    protected $name = '';
    protected static $instance = [];
    protected $pre = 'zzcms_';
    protected $is_validate = false;


    static public function getInstance()
    {
        $class_name = get_called_class();
        if (!isset(static::$instance[$class_name])) {
            static::$instance[$class_name] = new static();
        }
        return static::$instance[$class_name];
    }

    /**
     * 添加
     * @param $data
     * @return bool
     */
    public function addData(array $data)
    {
        $id = $this->isUpdate(false)->allowField(true)->save($data);
        if ($id) {
            return $this->id;
        } else {
            $this->error = '新增失败！';
            return false;
        }
    }

    /**
     * 编辑
     * @param type $data 提交数据
     * @return boolean
     */
    public function editData($data, $id = 0)
    {
        if (empty ($data)) {
            return false;
        }
        $id = $id ? $id : (int)$data[$this->pk];
        if (!$id) {
            $this->error = '参数不能为空！';
            return false;
        }
        $info = $this->get($id);
        if (empty ($info)) {
            $this->error = '信息不存在！';
            return false;
        }
        $data[$this->pk] = $id;
        if (false !== $this->isUpdate(true)->allowField(true)->save($data)) {
            return true;
        } else {
            $this->error = '编辑失败！';
            return false;
        }

    }

    /**
     * 删除
     * 适用于删除单条记录，其他删除请另外方法
     * @param $id
     * @return bool
     */
    public function deleteData($id)
    {
        if (empty ($id)) {
            $this->error = '参数不存在！';
            return false;
        }
        $info = $this->get($id);
        if (empty($info)) {
            $this->error = '信息不存在！';
            return false;
        }
        $num = $this->destroy($id);
        if ($num != 1) {
            $this->error = '删除错误！';
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取单条记录
     * @param $param 查询条件  可能为数组，也可能为数字（当为数字时视为主键）
     * @return array|bool
     * @throws \think\Exception
     */
    public function getOne($param, $option = [])
    {
        if (empty($param)) {
            return false;
        }
        $order = isset($option['order']) ? $option['order'] : "{$this->pk} desc";
        $field = isset($option['field']) ? $option['field'] : "*";
        $info = null;
        if (is_array($param)) {
            $info = $this->where($param)->field($field)->order($order)->find();
        } else {
            $id = intval($param);
            if ($id > 0) {
                $info = $this->order($order)->field($field)->find($id);
            }
        }
        return empty($info) ? [] : $info->toArray();
    }

    /**
     * 获取列表
     *
     * 列表调用示例： getList(['where'=>['cateid'=>3],'order'=>'id desc','limit'=>10,'field'=>'user_id,username','group'=>'keyid'])
     *
     * @param array $options 组合数组，包含各种默认值  可选择参数 支持 order,where,field,group,limit
     * @return array
     */
    public function getList($options = [])
    {
        // 排序
        $order = isset($options['order']) ? $options['order'] : "$this->pk desc";
        //查询条件
        $where = isset($options['where']) ? $options['where'] : [];
        //查询字段
        $field = isset($options['field']) ? $options['field'] : '*';
        //筛选
        $group = isset($options['group']) ? $options['group'] : '';
        //查询条数，当limit不传值时，默认获取前100条
        if (isset($options['limit']) && $options['limit'] == 'all') {
            $list = $this->where($where)->field($field)->group($group)->order($order)->select();
        } else {
            //查询条数，默认最多100条
            $limit = isset($options['limit']) ? intval($options['limit']) : 20;
            $list = $this->where($where)->field($field)->group($group)->order($order)->limit($limit)->select();
        }
        return empty($list) ? [] : $list->toArray();


    }


    /**
     * 返回分页信息
     * @param array $options $options 组合数组，包含各种默认值  可选择参数 支持 order,where,field,group,page,pagesize
     * @return \think\Paginator
     */
    public function getPager($options = [])
    {
        // 排序
        $order = isset($options['order']) ? $options['order'] : "$this->pk desc";
        //查询条件
        $where = isset($options['where']) ? $options['where'] : [];
        //查询字段
        $field = isset($options['field']) ? $options['field'] : '*';
        //筛选
        $group = isset($options['group']) ? $options['group'] : '';
        //分页大小
        $pagesize = isset($options['pagesize']) ? intval($options['pagesize']) : config('paginate.list_rows');
        return $this->where($where)->field($field)->group($group)->order($order)->paginate($pagesize);
    }


    /**
     * 管理后台。获取分页列表及总条数
     * @param $options
     * @return array
     */
    public function getInfo($options = [])
    {
        // 排序
        $order = isset($options['order']) ? $options['order'] : "$this->pk desc";
        //查询条件
        $where = isset($options['where']) ? $options['where'] : [];
        //查询字段
        $field = isset($options['field']) ? $options['field'] : '*';
        //筛选
        $group = isset($options['group']) ? $options['group'] : '';
        $request = app('request');
        //当前分页
        $page = $request->has('page') ? $request->param('page', 0, 'intval') : 1;
        //分页大小
        $pagesize = $request->has('limit') ? $request->param('limit', 3, 'intval') : 3;
        $count = $this->where($where)->count($this->pk);
        $list = $this->where($where)->field($field)->group($group)->order($order)->page($page, $pagesize)->select();
        $list = empty($list) ? [] : $list->toArray();
        //返回
        return ['count' => $count, 'data' => $list];
    }

    /**
     * 更新排序
     * @param $ids 以ID为键值的数组
     * @return bool
     */
    public function listorder($ids)
    {
        if (!is_array($ids)) {
            $this->error = '非法数据';
            return false;
        }
        foreach ($ids as $id => $listorder) {
            $this->where([$this->pk => $id])->setField(['listorder' => intval($listorder)]);
        }
        return true;
    }


    /**
     * 获取缓存，同时生成新的同名缓存 （以主键为键名）
     * @return array
     */
    public function getCache($options = [])
    {
        $order = isset($options['order']) ? $options['order'] : '';
        $where = isset($options['where']) ? $options['where'] : [];
        $list = $this->where($where)->order($order)->select();
        if (empty($list)) {
            cache($this->name, []);
            return [];
        }
        $array = [];
        foreach ($list as $item) {
            $array[$item[$this->pk]] = $item->toArray();
        }
        cache($this->name, $array);
        return $array;
    }

}